package com.example.easytraffic.core;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TrafficBuilder {

	private Runnable action;
	private Traffic traffic;
	
	public Traffic build() {
		return traffic;
	}

	public TrafficBuilder execute(Runnable action) {
		this.action = action;
		this.traffic = new SingleThreadedTraffic(action);
		return this;
	}
	
	public TrafficBuilder atMost(int times) {
		checkAction();
		this.action = new CountBasedProxyAction(action, times);
		this.traffic = new SingleThreadedTraffic(action);
		
		return this;
	}

	public TrafficBuilder timesPerExecution(int times) {
		checkTraffic();
		this.traffic = new CountBasedTraffic(traffic, times);
		return this;
	}
	
	public TrafficBuilder numberOfThreads(int numberOfThreads) {
		checkTraffic();
		this.traffic = new MultiThreadedTrafic(traffic, numberOfThreads);
		return this;
	}
	
	
	public TrafficBuilder withinRandomPeriod(long periodLimit, TimeUnit timeUnit) {
		checkTraffic();
		this.traffic = new RandomPeriodicTraffic(traffic, periodLimit, timeUnit);
		return this;
	}

	public TrafficBuilder withinPeriod(long period, TimeUnit timeUnit) {
		checkTraffic();
		this.traffic = new PeriodicTraffic(traffic, period, timeUnit);
		return this;
	}
	
	public TrafficBuilder after(long delay, TimeUnit timeUnit) {
		checkTraffic();
		this.traffic = new DelayedTraffic(traffic, delay, timeUnit);
		return this;
	}

	public TrafficBuilder at(Date scheduledDate) {
		checkTraffic();
		this.traffic = new ScheduledTraffic(traffic, scheduledDate);
		return this;
	}
	
	public TrafficBuilder for_(long duration, TimeUnit timeUnit) {
		checkTraffic();
		this.traffic = new DurationalTraffic(traffic, duration, timeUnit);
		return this;
	}

	private void checkAction() {
		if (action == null) {
			throw new TrafficBuilderException("Action is null; first call do_().");
		}
	}

	private void checkTraffic() {
		if (traffic == null) {
			throw new TrafficBuilderException("Traffic is null; first call do_().");
		}
	}

}
